//
//  PGLocalFileManager.m
//  PhotographicGuide
//
//  Created by indream on 13-2-23.
//  Copyright (c) 2013年 indream. All rights reserved.
//

#import "PGLocalFileManager.h"
#import "CommonCrypto/CommonDigest.h"
static PGLocalFileManager *_instance;
@implementation PGLocalFileManager

#pragma mark - public
-(BOOL)fileIsExist:(NSString*)fileURL{
    return [[NSFileManager defaultManager]fileExistsAtPath:[self pathForDocument:fileURL]];
}
-(NSData*)fileWithURL:(NSString*)fileURL{
    return [[NSFileManager defaultManager]contentsAtPath:[self pathForDocument:fileURL]];;
}
-(BOOL)saveFile:(NSData*)data withFileURL:(NSString*)fileURL{
    NSString*filePath = [self pathForDocument:fileURL];
    BOOL status =  [[NSFileManager defaultManager]createFileAtPath:filePath contents:data attributes:nil];
    return status;
}

-(void)removeFileWithURL:(NSString*)fileURL{
    if([self fileIsExist:fileURL]){
        NSString*filePath = [self pathForDocument:fileURL];
        [[NSFileManager defaultManager]removeItemAtPath:filePath error:nil];
    }
}
-(NSString*)pathForDocument:(NSString*)fileURL{
    NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString*filePath = [self MD5Hash:fileURL withMime:@"file"];
    [[NSFileManager defaultManager]createDirectoryAtPath:[[docDir stringByAppendingString:@"/"]stringByAppendingString:[[filePath componentsSeparatedByString:@"/"]objectAtIndex:0]] withIntermediateDirectories:NO attributes:nil error:nil];
    return [docDir stringByAppendingPathComponent:filePath];
}
#pragma mark - util
- (NSString *)MD5Hash:(NSString*)fileName withMime:(NSString*)mime{
    const char *cStr = [fileName UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, strlen(cStr), result );
    return [NSString stringWithFormat: @"%02X%02X/%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X.%@",
            result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11], result[12], result[13], result[14], result[15],mime ];
}
//校验jpeg文件是否正确
-(int)isJPEGValid:(NSString *)jpegUrl
{
    NSData*jpeg = [self fileWithURL:jpegUrl];
    if ([jpeg length] < 4)
        return 1;
    const unsigned char * bytes = (const unsigned char *)[jpeg bytes];
    if (bytes[0] != 0xFF || bytes[1] != 0xD8) return 2;
    if (bytes[[jpeg length] - 2] != 0xFF ||
        bytes[[jpeg length] - 1] != 0xD9) return 3;
    return 0;
}
+(PGLocalFileManager*)sharedManager{
    if(_instance==nil){
        _instance = [[PGLocalFileManager alloc]init];
    }
    return _instance;
}
@end
